package com.bdbit.ChargingStation.Utils;

import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Map.Entry;

import com.bdbit.ChargingStation.entity.bean_order;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

/*
 * 利用HttpClient进行post请求的工具类
 */
@Component
public class HttpClientUtil {
    public static String doPost(int type, String url, Map<String, String> map, String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            if (type == 0) {
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                httpPost.setHeader("App-Key", "sfci50a7sy4xi");

                SHA1 sha1 = new SHA1();
                int random = sha1.getRandom();
                long timestamp = TimeUtils.getCurTimeLong();
                String sha1Key = sha1.getKey(random, timestamp);

                httpPost.setHeader("Nonce", "" + random);
                httpPost.setHeader("Timestamp", "" + timestamp);
                httpPost.setHeader("Signature", sha1Key);

                //设置参数
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                Iterator iterator = map.entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry<String, Object> elem = (Entry<String, Object>) iterator.next();
                    list.add(new BasicNameValuePair(elem.getKey(), elem.getValue().toString()));
                }
                if (list.size() > 0) {
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                    httpPost.setEntity(entity);
                }
            } else {
                httpPost.setHeader("Content-Type", "application/json");
                //创建StringEntity(json)
                String json = GsonUtils.ModuleTojosn(map);
                HttpEntity entity = new StringEntity(json,charset);
                httpPost.setEntity(entity);
            }

            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static String doPostJson(String url,
                                    bean_order oeder, String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);

            httpPost.setHeader("Content-Type", "application/json");
            //创建StringEntity(json)
            String json = GsonUtils.ModuleTojosn(oeder);
            HttpEntity entity = new StringEntity(json,charset);
            httpPost.setEntity(entity);


            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public Map<String, Object> toMap(bean_order order) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = order.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object fieldValue = field.get(order);
            map.put(fieldName, fieldValue);
        }
        return map;
    }

    public static String doPostHttps(String url, Map<String, Object> map, String charset) {
        SkipHttpsUtil skipHttpsUtil = new SkipHttpsUtil();
        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        httpclient = (CloseableHttpClient) SkipHttpsUtil.wrapClient();
        HttpPost httpPost = null;
        String result = null;
        try {
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, Object> elem = (Entry<String, Object>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue().toString()));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            response = httpclient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    /**
     * md5加密
     *
     * @param str
     * @return
     */
    public static String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (byte element : byteDigest) {
                i = element;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            // 32位加密
            return buf.toString().toUpperCase();
            // 16位的加密
            // return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
